<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/hexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="开发笔记,">










<meta name="description" content="嗯，终于准备开始写微服务了，先声明下，这里因为是初探，只能算是小小小有所悟，能介绍的内容也不多，当然我也没有实战项目的经验，所以肯定会有很多写的不好的地方，所以，欢迎拍砖！！其实我写技术类的博客，一般偏工具类居多，框架类的很少，平时看别人写的技术博客和文章，也不爱看框架类的东西，除非是知名大V写的东西，不然我不敢确定他写出来的东西是不是对的，或者是不是最优的，我始终觉得对于新学的东西，初次的印象非">
<meta name="keywords" content="开发笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="初探.net core微服务">
<meta property="og:url" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/index.html">
<meta property="og:site_name" content="Tony&#39;s blog">
<meta property="og:description" content="嗯，终于准备开始写微服务了，先声明下，这里因为是初探，只能算是小小小有所悟，能介绍的内容也不多，当然我也没有实战项目的经验，所以肯定会有很多写的不好的地方，所以，欢迎拍砖！！其实我写技术类的博客，一般偏工具类居多，框架类的很少，平时看别人写的技术博客和文章，也不爱看框架类的东西，除非是知名大V写的东西，不然我不敢确定他写出来的东西是不是对的，或者是不是最优的，我始终觉得对于新学的东西，初次的印象非">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/consul.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/consul_http.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/service1.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/consul_service1.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/%E7%86%94%E6%96%AD%E9%99%8D%E7%BA%A7.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/%E7%86%94%E6%96%AD.jpg">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/consul_service_all.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/ret1.png">
<meta property="og:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/ret2.png">
<meta property="og:updated_time" content="2019-11-28T00:52:14.010Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="初探.net core微服务">
<meta name="twitter:description" content="嗯，终于准备开始写微服务了，先声明下，这里因为是初探，只能算是小小小有所悟，能介绍的内容也不多，当然我也没有实战项目的经验，所以肯定会有很多写的不好的地方，所以，欢迎拍砖！！其实我写技术类的博客，一般偏工具类居多，框架类的很少，平时看别人写的技术博客和文章，也不爱看框架类的东西，除非是知名大V写的东西，不然我不敢确定他写出来的东西是不是对的，或者是不是最优的，我始终觉得对于新学的东西，初次的印象非">
<meta name="twitter:image" content="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/consul.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hexo/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Tony'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tony_df.coding.net/2019/11/27/初探-net-core微服务/">





  <title>初探.net core微服务 | Tony's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hexo/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学着码代码,学着码人生;</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tony_df.coding.net/hexo/2019/11/27/初探-net-core微服务/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hexo/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">初探.net core微服务</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-11-27T09:51:51+08:00">
                2019-11-27
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>嗯，终于准备开始写微服务了，先声明下，这里因为是初探，只能算是小小小有所悟，能介绍的内容也不多，当然我也没有实战项目的经验，所以肯定会有很多写的不好的地方，所以，欢迎拍砖！！<br>其实我写技术类的博客，一般偏工具类居多，框架类的很少，平时看别人写的技术博客和文章，也不爱看框架类的东西，除非是知名大V写的东西，不然我不敢确定他写出来的东西是不是对的，或者是不是最优的，我始终觉得对于新学的东西，初次的印象非常重要，而工具不一样，工具类是一种开箱即用的技术，几乎是放之四海皆准，我分享的只是一种封箱的过程，提供的是一种解决问题的思路，从而可以从某个角度切入系统，高效的解决某些常见的问题。<br>而框架不一样，可以说我们做系统，做软件，框架的选择一旦决定，整个的系统风格，也就差不多定了，就像设计师设计大楼一样，设计图纸是经过多方敲定的，一旦开始施工，便要严格按照图纸规范来施工，比如钢材用什么样的，玻璃的防震等级是几级，层高多少，水泥的石灰砂石比等等，都是不能随意修改的。同样的，系统开发框架也是一样，因为框架本身就是一种经过验证的软件开发的半成品，比如我们常说的.net mvc，spring，yii，rails，以及前端用到的jQuery，vue等，也因此，如果我们想在自己的项目里使用框架，便需要遵循框架的诸多约定，不能随意挥洒，注意，遵循这种约定并不是限制开发能力，反而是因为遵循了这些约定，才会更大限度的发挥框架的作用，更好的完成我们的项目。因此上升到框架的层面，大多是需要有经验的高级程序员或者是架构师级别的工程师，写出来的东西，才会让人信服，因为在框架的应用上，成熟的项目经验非常重要。（我写微服务可不是想证明我高级，充其量算总结吧）<br>而今天我们要说的微服务呢，我觉得它也不能算框架，它跟像是是多个框架的交叉在一起的产物，所以人们常说微服务架构，但最近这个概念炒得实在是太火了，而且不管是大厂小厂，都在用，是一种实实在在的火，所以我也想凑个热闹。<br>哈哈，一不小心又扯多了，来来，咱们聊微服务。<br>关于微服务的具体介绍呢，只要你不是那么闭塞，肯定也看过不少，不论是技术类公号，还是微博或者博客上，大V们说的肯定都比我全面，所以，我这就分享一篇吧，传送门:<a href="https://www.zhihu.com/question/65502802?sort=created" target="_blank" rel="noopener">https://www.zhihu.com/question/65502802?sort=created</a>，这是知乎上的一篇，图片介绍很丰富，内容也很通俗幽默。</p>
<p>目前.net 生态里好像还没有像spring cloud那种云原生开发框架的集大成者出现（可能我见识短浅），所以，我们在搭建微服务架构时需要的开发组件，得自己安装。<br>首先，我们要有一个服务注册中心，可能目前比较常用的是consul和zookeeper，他们都支持集群部署，对容器的支持也很好，这里我用的是consul。<br>先到consul的官网<a href="https://www.consul.io/" target="_blank" rel="noopener">https://www.consul.io/</a>去下载对应开发环境的软件（这里就不具体介绍consul了，大家可以到官网去查看，consul的功能还是很强大的，因为我了解的也不多，所以这里就简单介绍）。</p>
<p>开发环境下启动consul</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">consul.exe agent -dev</span><br></pre></td></tr></table></figure>

<p><img src="consul.png" alt="consul"><br>看到图片中标红的提示，说明consul已经正常启动了，consul启动后，会有一个占用8500端口的http服务随之启动，可以打开浏览器<a href="http://127.0.0.1:8500/" target="_blank" rel="noopener">http://127.0.0.1:8500/</a>，查看consul的配置界面。<br><img src="consul_http.png" alt="consul_http"><br>然后我们创建一个.net core mvc项目，使其注册到consul中心<br>我们新建一个控制器，当做consul的心跳检查机制（具体可查看consul文档）的访问接口，</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">[<span class="meta">Route(<span class="meta-string">"api/[controller]"</span>)</span>]</span><br><span class="line">[<span class="meta">ApiController</span>]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">HealthController</span> : <span class="title">ControllerBase</span></span><br><span class="line">&#123;</span><br><span class="line">    [<span class="meta">HttpGet</span>]</span><br><span class="line">    <span class="function"><span class="keyword">public</span> IActionResult <span class="title">Get</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> Ok(<span class="string">"ok"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后在项目里添加consul引用，可在包管理控制台直接输入”install-package consul”，也可以在nuget包管理器搜索consul安装<br>修改一下program.cs</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> IHostBuilder <span class="title">CreateHostBuilder</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">var</span> config = <span class="keyword">new</span> ConfigurationBuilder()</span><br><span class="line">        .AddCommandLine(args)</span><br><span class="line">        .Build();</span><br><span class="line">    String ip = <span class="keyword">string</span>.IsNullOrEmpty(config[<span class="string">"ip"</span>]) ? <span class="string">"127.0.0.1"</span> : config[<span class="string">"ip"</span>];</span><br><span class="line">    String port = config[<span class="string">"port"</span>];</span><br><span class="line">    RestTools.StaticParams.service_id = Guid.NewGuid().ToString();<span class="comment">//服务编号，提前生成的目的是作为key，标记ip和端口存到redis</span></span><br><span class="line">    <span class="keyword">if</span> (port == <span class="string">"0"</span> || <span class="keyword">string</span>.IsNullOrEmpty(port))</span><br><span class="line">    &#123;</span><br><span class="line">        port = RestTools.Tools.GetRandAvailablePort().ToString();<span class="comment">//该方法是随机寻找一个没有被占用的端口，也可以自己指定一个</span></span><br><span class="line">    &#125;</span><br><span class="line">    redis.StringSet(RestTools.StaticParams.service_id, ip + <span class="string">":"</span> + port);</span><br><span class="line">    <span class="keyword">return</span> Host.CreateDefaultBuilder(args)</span><br><span class="line">        .ConfigureWebHostDefaults(webBuilder =&gt;</span><br><span class="line">        &#123;</span><br><span class="line">            webBuilder.UseStartup&lt;Startup&gt;()</span><br><span class="line">            .UseUrls(<span class="string">$"http://<span class="subst">&#123;ip&#125;</span>:<span class="subst">&#123;port&#125;</span>"</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ConfigurationOverview</span>(<span class="params">ConsulClientConfiguration obj</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    obj.Address = <span class="keyword">new</span> Uri(<span class="string">"http://127.0.0.1:8500"</span>);</span><br><span class="line">    obj.Datacenter = <span class="string">"datacenter"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后修改startup.cs文件里Configure方法，注册相关服务</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Configure</span>(<span class="params">IApplicationBuilder app, IWebHostEnvironment env</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (env.IsDevelopment())</span><br><span class="line">    &#123;</span><br><span class="line">        app.UseDeveloperExceptionPage();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    app.UseRouting();</span><br><span class="line"></span><br><span class="line">    app.UseAuthorization();</span><br><span class="line"></span><br><span class="line">    app.UseEndpoints(endpoints =&gt;</span><br><span class="line">    &#123;</span><br><span class="line">        endpoints.MapControllers();</span><br><span class="line">    &#125;);</span><br><span class="line">    <span class="keyword">string</span> address = redis.StringGet(RestTools.StaticParams.service_id);</span><br><span class="line">    <span class="keyword">string</span> ip = address.Split(<span class="string">':'</span>)[<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">int</span> port = Convert.ToInt32(address.Split(<span class="string">':'</span>)[<span class="number">1</span>]);</span><br><span class="line">    ConsulClient client = <span class="keyword">new</span> ConsulClient(ConfigurationOverview);</span><br><span class="line">    Task&lt;WriteResult&gt; result = client.Agent.ServiceRegister(<span class="keyword">new</span> AgentServiceRegistration()</span><br><span class="line">    &#123;</span><br><span class="line">        ID = <span class="string">"MsgService"</span> + RestTools.StaticParams.service_id,<span class="comment">//服务编号，不能重复，用Guid最简单</span></span><br><span class="line">        Name = <span class="string">"MsgService"</span>,<span class="comment">//服务的名字</span></span><br><span class="line">        Address = ip,<span class="comment">//我的ip地址(可以被其他应用访问的地址，本地测试可以用127.0.0.1，机房环境中一定要写自己的内网ip地址)</span></span><br><span class="line">        Port = port,<span class="comment">//我的端口</span></span><br><span class="line">        Check = <span class="keyword">new</span> AgentServiceCheck()</span><br><span class="line">        &#123;</span><br><span class="line">            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(<span class="number">5</span>),<span class="comment">//服务停止多久后反注册</span></span><br><span class="line">            Interval = TimeSpan.FromSeconds(<span class="number">10</span>),<span class="comment">//健康检查时间间隔，或者称为心跳间隔</span></span><br><span class="line">            HTTP = <span class="string">$"http://<span class="subst">&#123;ip&#125;</span>:<span class="subst">&#123;port&#125;</span>/api/health"</span>,<span class="comment">//健康检查地址,</span></span><br><span class="line">            Timeout = TimeSpan.FromSeconds(<span class="number">5</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后，注意不要使用iis或者iisexpress，以控制台的方式启动项目(kestrel)，<br><img src="service1.png" alt="service1"><br>然后我们打开刚才的consul管理界面，可以看到我们刚注册的服务已经出现了<br><img src="consul_service1.png" alt="consul_service1"></p>
<p>接着，来说说，熔断降级，后边会说到Ocelot框架，其实本身Ocelot里集成了熔断降级相关的组件，通过简单配置即可，但是吧。。。这个Ocelot的官方文档，是英文版的，额，我也是在继续学习中，目前对于Ocelot了解甚少，只是对其网关组件相对熟悉，其他还是懵逼状态，所以就把熔断降级单拎出来说一下，当然，能单拎出来，也是通过学习别的大牛的博客<a href="https://www.cnblogs.com/wyt007/p/9150116.html" target="_blank" rel="noopener">https://www.cnblogs.com/wyt007/p/9150116.html</a>介绍，在稍加总结得来的。好了，这些就不多说了，看东西吧。</p>
<p>关于熔断降级，我们需要使用到Polly（.net 基金会认可并推荐的一个库）<br>看下代码吧，<br>在控制台程序里，首先引用polly和AspectCore（哎呀，真是越写东西越多），aspectcore是一个AOP框架，我们可以在项目里引用它，方便的在方法中实现全局拦截，有点像写webapi时用到的请求拦截，目的是使系统保持原有清晰的业务逻辑，降低耦合性，提高代码重用性。<br>首先创建一个拦截类（东西有点多，但好多都是框架文档里原生的东西，我这直接拿过来的，如果觉得看我写的东西渣，可以去看文档）</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line"><span class="comment"><span class="doctag">///</span> 熔断框架</span></span><br><span class="line"><span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">[<span class="meta">AttributeUsage(AttributeTargets.Method)</span>]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">HystrixCommandAttribute</span> : <span class="title">AbstractInterceptorAttribute</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="meta">#<span class="meta-keyword">region</span> 属性</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 最多重试几次，如果为0则不重试</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> MaxRetryTimes &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125; = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 重试间隔的毫秒数</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> RetryIntervalMilliseconds &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125; = <span class="number">100</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 是否启用熔断</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">bool</span> EnableCircuitBreater &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125; = <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 熔断前出现允许错误几次</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> ExceptionAllowedBeforeBreaking &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125; = <span class="number">3</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 熔断多长时间（毫秒 ）</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> MillisecondsOfBreak &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125; = <span class="number">1000</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 执行超过多少毫秒则认为超时（0表示不检测超时）</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> TimeOutMilliseconds &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125; = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 缓存多少毫秒（0表示不缓存），用“类名+方法名+所有参数ToString拼接”做缓存Key</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> CacheTTLMilliseconds &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125; = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> IAsyncPolicy policy;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//缓存</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">readonly</span> Microsoft.Extensions.Caching.Memory.IMemoryCache memoryCache = <span class="keyword">new</span> Microsoft.Extensions.Caching.Memory.MemoryCache(<span class="keyword">new</span> Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 降级方法名</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">string</span> FallBackMethod &#123; <span class="keyword">get</span>; <span class="keyword">set</span>; &#125;</span><br><span class="line">    <span class="meta">#<span class="meta-keyword">endregion</span></span></span><br><span class="line"></span><br><span class="line">    <span class="meta">#<span class="meta-keyword">region</span> 构造函数</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 熔断框架</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;param name="fallBackMethod"&gt;</span>降级方法名<span class="doctag">&lt;/param&gt;</span></span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">HystrixCommandAttribute</span>(<span class="params"><span class="keyword">string</span> fallBackMethod</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">this</span>.FallBackMethod = fallBackMethod;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">#<span class="meta-keyword">endregion</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">async</span> Task <span class="title">Invoke</span>(<span class="params">AspectContext context, AspectDelegate next</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="comment">//一个HystrixCommand中保持一个policy对象即可</span></span><br><span class="line">        <span class="comment">//其实主要是CircuitBreaker要求对于同一段代码要共享一个policy对象</span></span><br><span class="line">        <span class="comment">//根据反射原理，同一个方法就对应一个HystrixCommandAttribute，无论几次调用，</span></span><br><span class="line">        <span class="comment">//而不同方法对应不同的HystrixCommandAttribute对象，天然的一个policy对象共享</span></span><br><span class="line">        <span class="comment">//因为同一个方法共享一个policy，因此这个CircuitBreaker是针对所有请求的。</span></span><br><span class="line">        <span class="comment">//Attribute也不会在运行时再去改变属性的值，共享同一个policy对象也没问题</span></span><br><span class="line">        <span class="keyword">lock</span> (<span class="keyword">this</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">if</span> (policy == <span class="literal">null</span>)</span><br><span class="line">            &#123;</span><br><span class="line">                policy = Policy.Handle&lt;Exception&gt;()</span><br><span class="line">                    .FallbackAsync(<span class="keyword">async</span> (ctx, t) =&gt; <span class="keyword">await</span> Task.Run(() =&gt;</span><br><span class="line">                    &#123;</span><br><span class="line">                        AspectContext aspectContext = (AspectContext)ctx[<span class="string">"aspectContext"</span>];</span><br><span class="line">                        <span class="keyword">var</span> fallBackMethod = context.ServiceMethod.DeclaringType.GetMethod(<span class="keyword">this</span>.FallBackMethod);</span><br><span class="line">                        Object fallBackResult = fallBackMethod.Invoke(context.Implementation, context.Parameters);</span><br><span class="line">                        <span class="comment">//不能如下这样，因为这是闭包相关，如果这样写第二次调用Invoke的时候context指向的</span></span><br><span class="line">                        <span class="comment">//还是第一次的对象，所以要通过Polly的上下文来传递AspectContext</span></span><br><span class="line">                        <span class="comment">//context.ReturnValue = fallBackResult;</span></span><br><span class="line">                        aspectContext.ReturnValue = fallBackResult;</span><br><span class="line">                    &#125;), <span class="keyword">async</span> (ex, t) =&gt; <span class="keyword">await</span> Task.Run(() =&gt; &#123; &#125;));</span><br><span class="line">                <span class="keyword">if</span> (MaxRetryTimes &gt; <span class="number">0</span>)<span class="comment">//重试</span></span><br><span class="line">                &#123;</span><br><span class="line">                    policy = policy.WrapAsync(Policy.Handle&lt;Exception&gt;().WaitAndRetryAsync(MaxRetryTimes, i =&gt; TimeSpan.FromMilliseconds(RetryIntervalMilliseconds)));</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (EnableCircuitBreater)<span class="comment">//熔断</span></span><br><span class="line">                &#123;</span><br><span class="line">                    policy = policy.WrapAsync(Policy.Handle&lt;Exception&gt;().CircuitBreakerAsync(ExceptionAllowedBeforeBreaking, TimeSpan.FromMilliseconds(MillisecondsOfBreak)));</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (TimeOutMilliseconds &gt; <span class="number">0</span>)<span class="comment">//超时</span></span><br><span class="line">                &#123;</span><br><span class="line">                    policy = policy.WrapAsync(Policy.TimeoutAsync(() =&gt; TimeSpan.FromMilliseconds(TimeOutMilliseconds), Polly.Timeout.TimeoutStrategy.Pessimistic));</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//把本地调用的AspectContext传递给Polly,主要给FallBackMethod中使用，避免闭包的坑</span></span><br><span class="line">        Context pollyCtx = <span class="keyword">new</span> Context();</span><br><span class="line">        pollyCtx[<span class="string">"aspectContext"</span>] = context;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (CacheTTLMilliseconds &gt; <span class="number">0</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="comment">//用类名+方法名+参数的下划线连接起来作为缓存key</span></span><br><span class="line">            <span class="keyword">string</span> cacheKey = <span class="string">"HystrixMethodCacheManager_Key_"</span> + context.ServiceMethod.DeclaringType + <span class="string">"."</span> + context.ServiceMethod + <span class="keyword">string</span>.Join(<span class="string">"_"</span>, context.Parameters);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//尝试去缓存中获取。如果找到了，则直接用缓存中的值做返回值</span></span><br><span class="line">            <span class="keyword">if</span> (memoryCache.TryGetValue(cacheKey, <span class="keyword">out</span> <span class="keyword">var</span> cacheValue))</span><br><span class="line">            &#123;</span><br><span class="line">                context.ReturnValue = cacheValue;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">            &#123;</span><br><span class="line">                <span class="comment">//如果缓存中没有，则执行实际被拦截的方法</span></span><br><span class="line">                <span class="keyword">await</span> policy.ExecuteAsync(ctx =&gt; next(context), pollyCtx);</span><br><span class="line">                <span class="comment">//存入缓存中</span></span><br><span class="line">                <span class="keyword">using</span> (<span class="keyword">var</span> cacheEntry = memoryCache.CreateEntry(cacheKey))</span><br><span class="line">                &#123;</span><br><span class="line">                    cacheEntry.Value = context.ReturnValue;</span><br><span class="line">                    cacheEntry.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMilliseconds(CacheTTLMilliseconds);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span><span class="comment">//如果没有启用缓存，就直接执行业务方法</span></span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">await</span> policy.ExecuteAsync(ctx =&gt; next(context), pollyCtx);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们编写一个Person类（aspect文档里的例子，稍加改造）</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Person</span></span><br><span class="line">&#123;</span><br><span class="line">    [<span class="meta">HystrixCommand(nameof(HelloFallbackAsync), MaxRetryTimes = 3, EnableCircuitBreater = true)</span>]</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">async</span> Task&lt;<span class="keyword">string</span>&gt; <span class="title">HelloAsync</span>(<span class="params"><span class="keyword">string</span> name</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"Hello,"</span> + name);</span><br><span class="line"></span><br><span class="line">        <span class="meta">#<span class="meta-keyword">region</span> 抛错</span></span><br><span class="line">        String s = <span class="literal">null</span>;</span><br><span class="line">        s.ToString();</span><br><span class="line">        <span class="meta">#<span class="meta-keyword">endregion</span></span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="string">"ok"</span> + name;</span><br><span class="line">    &#125;</span><br><span class="line">    [<span class="meta">HystrixCommand(nameof(Hello2FallbackAsync))</span>]</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">async</span> Task&lt;<span class="keyword">string</span>&gt; <span class="title">HelloFallbackAsync</span>(<span class="params"><span class="keyword">string</span> name</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"降级等级1,"</span> + name);</span><br><span class="line">        <span class="keyword">string</span> s = <span class="literal">null</span>;</span><br><span class="line">        s.ToString();</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"fail_1"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">async</span> Task&lt;<span class="keyword">string</span>&gt; <span class="title">Hello2FallbackAsync</span>(<span class="params"><span class="keyword">string</span> name</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"降级等级2,"</span> + name);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"fail_2"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    [<span class="meta">HystrixCommand(nameof(FallAdd))</span>]</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">int</span> <span class="title">Add</span>(<span class="params"><span class="keyword">int</span> i, <span class="keyword">int</span> j</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="comment">//string s = null;</span></span><br><span class="line">        <span class="comment">//s.ToString();</span></span><br><span class="line">        <span class="keyword">return</span> i + j;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">int</span> <span class="title">FallAdd</span>(<span class="params"><span class="keyword">int</span> i, <span class="keyword">int</span> j</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    [<span class="meta">HystrixCommand(nameof(TestFallBack), CacheTTLMilliseconds = 3000)</span>]</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">Test</span>(<span class="params"><span class="keyword">int</span> i</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"Test,"</span> + i);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="keyword">void</span> <span class="title">TestFallBack</span>(<span class="params"><span class="keyword">int</span> i</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        Console.WriteLine(<span class="string">"Test"</span> + i);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后在program.cs主函数里编写</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    ProxyGeneratorBuilder proxyGeneratorBuilder = <span class="keyword">new</span> ProxyGeneratorBuilder();</span><br><span class="line">    <span class="keyword">using</span> (IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build())</span><br><span class="line">    &#123;</span><br><span class="line">        Person p = proxyGenerator.CreateClassProxy&lt;Person&gt;();</span><br><span class="line">        Console.WriteLine(p.HelloAsync(<span class="string">"Hello World"</span>).Result);</span><br><span class="line">        Console.WriteLine(p.Add(<span class="number">1</span>, <span class="number">2</span>));</span><br><span class="line">        <span class="keyword">while</span> (<span class="literal">true</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(p.HelloAsync(<span class="string">"Hello World"</span>).Result);</span><br><span class="line">            Thread.Sleep(<span class="number">100</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行看下效果<br><img src="%E7%86%94%E6%96%AD%E9%99%8D%E7%BA%A7.png" alt="熔断降级.png"><br>关于aspect，我这里只是一笔带过，其中还有很多值得深究的东西受制于篇幅，以及当前的知识面，就没多说，这一块如果您已经是微服务的高手了，可以直接忽略，小白同学，可以直接把我灌得这几款代码放到项目里运行，然后在体会一下熔断降级的概念。<br>在分享一张熔断器的设计图<br><img src="%E7%86%94%E6%96%AD.jpg" alt="熔断.jpg"><br>好了，我们继续回到框架上来吧，前面提到了Ocelot，我们用Ocelot来做个测试网关，集成前面在consul注册的服务。<br>我们新建一个网站项目，然后分别引用Ocelot和Ocelot.Provider.Consul两个包，<br>然后新建configuration.json文件(这个文件里的具体参数解释，Ocelot的文档里都有，我在注释里简单介绍下)</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"ReRoutes"</span>: [</span><br><span class="line">    &#123;</span><br><span class="line">      "DownstreamPathTemplate": "/api/sms/&#123;url&#125;",//下游请求链接，也就是转发的地址</span><br><span class="line">      "DownstreamScheme": "http",</span><br><span class="line">      "DownstreamHostAndPorts": [</span><br><span class="line">        &#123;</span><br><span class="line">          "Host": "10.185.1.41", //服务的地址</span><br><span class="line">          "Port": 39688   //服务的端口</span><br><span class="line">        &#125;</span><br><span class="line">      ],</span><br><span class="line">      "UpstreamPathTemplate": "/sms/&#123;url&#125;",//上游地址，也就是通过网关直接访问的地址</span><br><span class="line">      "UpstreamHttpMethod": [ "Get", "Post" ],//识别的请求方式</span><br><span class="line">      "ServiceName": "MsgService",//在consul里注册的服务名称</span><br><span class="line">      "LoadBalancerOptions": &#123;</span><br><span class="line">        "Type": "RoundRobin"</span><br><span class="line">      &#125;,</span><br><span class="line">      "UseServiceDiscovery": true</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="attr">"DownstreamPathTemplate"</span>: <span class="string">"/api/email/&#123;url&#125;"</span>,</span><br><span class="line">      <span class="attr">"DownstreamScheme"</span>: <span class="string">"http"</span>,</span><br><span class="line">      <span class="attr">"DownstreamHostAndPorts"</span>: [</span><br><span class="line">        &#123;</span><br><span class="line">          <span class="attr">"Host"</span>: <span class="string">"localhost"</span>,</span><br><span class="line">          <span class="attr">"Port"</span>: <span class="number">29216</span></span><br><span class="line">        &#125;</span><br><span class="line">      ],</span><br><span class="line">      <span class="attr">"UpstreamPathTemplate"</span>: <span class="string">"/email/&#123;url&#125;"</span>,</span><br><span class="line">      <span class="attr">"UpstreamHttpMethod"</span>: [ <span class="string">"Get"</span>, <span class="string">"Post"</span> ],</span><br><span class="line">      <span class="attr">"ServiceName"</span>: <span class="string">"EmailService"</span>,</span><br><span class="line">      <span class="attr">"LoadBalancerOptions"</span>: &#123;</span><br><span class="line">        <span class="attr">"Type"</span>: <span class="string">"RoundRobin"</span></span><br><span class="line">      &#125;,</span><br><span class="line">      <span class="attr">"UseServiceDiscovery"</span>: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  ],</span><br><span class="line">  "GlobalConfiguration": &#123;</span><br><span class="line">    "ServiceDiscoveryProvider": &#123;</span><br><span class="line">      "Host": "127.0.0.1",</span><br><span class="line">      "Port": 8500</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们在program.cs里修改CreateHostBuilder</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> IHostBuilder <span class="title">CreateHostBuilder</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span> =&gt;</span><br><span class="line">    Host.CreateDefaultBuilder(args)</span><br><span class="line">        .ConfigureWebHostDefaults(webBuilder =&gt;</span><br><span class="line">        &#123;</span><br><span class="line">            webBuilder.UseStartup&lt;Startup&gt;();</span><br><span class="line">        &#125;).ConfigureAppConfiguration(conf =&gt;</span><br><span class="line">        &#123;</span><br><span class="line">            conf.AddJsonFile(<span class="string">"configuration.json"</span>, optional: <span class="literal">false</span>, reloadOnChange: <span class="literal">true</span>);</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>

<p>接着在startup.cs里引入<br>using Ocelot.DependencyInjection;<br>using Ocelot.Middleware;<br>using Ocelot.Provider.Consul;<br>三个命名空间，然后修改ConfigureServices和Configuration</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ConfigureServices</span>(<span class="params">IServiceCollection services</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    services.AddControllers();</span><br><span class="line">    services.AddOcelot()</span><br><span class="line">    .AddConsul();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Configure</span>(<span class="params">IApplicationBuilder app, IWebHostEnvironment env</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (env.IsDevelopment())</span><br><span class="line">    &#123;</span><br><span class="line">        app.UseDeveloperExceptionPage();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    app.UseRouting();</span><br><span class="line"></span><br><span class="line">    app.UseAuthorization();</span><br><span class="line"></span><br><span class="line">    app.UseOcelot().Wait();<span class="comment">//不要忘了写Wait</span></span><br><span class="line"></span><br><span class="line">    app.UseEndpoints(endpoints =&gt;</span><br><span class="line">    &#123;</span><br><span class="line">        endpoints.MapControllers();</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后启动项目，因为我们之前注册了MsgService服务，同样的方式在注册一个EmailServices服务<br>注册完成后，在consul配置节目看到如下结果<br><img src="consul_service_all.png" alt="consul_service_all"><br>接着我们可以试一下Ocelot为我们提供的网关效果，比如，我在浏览器地址栏输入<a href="http://localhost:5000/sms/send?msg=我是转发来的" target="_blank" rel="noopener">http://localhost:5000/sms/send?msg=我是转发来的</a><br><img src="ret1.png" alt="ret1"><br>效果和直接请求服务<a href="http://10.185.1.41:39688/api/sms/send?msg=我是转发来的" target="_blank" rel="noopener">http://10.185.1.41:39688/api/sms/send?msg=我是转发来的</a>效果是一样的，但是Ocelot帮我们做好了转发，所以只需要根据在配置文件里输入的上游请求模板，即可得到从该服务处获取的数据<br>再看下MsgService打印的数据结果<br><img src="ret2.png" alt="ret2"><br>呼，就到这吧，真是书到用时方恨少，写不动了。。。还得再多看这些知识。<br>最后总结下，微服务的架构，我在前面推荐的文章里也提到了，有利有弊，我觉得最大的弊端，不是开发上的，而是沟通上的，因为微服务这个东西，不是说你自己一个人想架构就能架构起来的，而是要和团队协商好，真正的拆分已有的业务模型，掌控好拆分的粗细粒度，甚至连库表结构都要拆分，是一个需要从长计议的事情，也因此，很多公司短时间内没办法转型到微服务，或者其他架构，而在我看来，这也是区分一个团队价值的地方，如果一个团队里全是热血向上的好青年，他们对技术，对产品有着极致的追求，那这种转型，对他们来说剩下的就仅仅是时间问题了，而如果跳不出舒适圈，总是原地踏步的话，难免会随着时间的推移被历史所淘汰，所谓温水煮青蛙，现实就是这么滴残酷，逆水行舟，不进则退。我个人认为如果公司的业务规模足够，而且你的团队确实出现了一些同时维护多个单体应用所带来的的一些弊端，还是有必要下决心转型到微服务架构上来的，一是的确会提高整体的系统水平，而是对团队开发能力的提升也是有极大的帮助，如果只做单体应用，难免成为一个只会写网站，写软件的普通程序员，当下的技术环境，会写网站写软件，已经不算是加分项了，慢慢变成了一个基本技能，如果想提高，无非就是两头发展，一是深入底层，了解底层结构，比如某个框架的底层实现，语法糖的封装原理，各类算法等等，再有就是向上，提高认知水平，从更高的层面来掌控系统，比如架构设计，技术选型等等，当然这两条看似相反的路，其实是相同的，只有两条路都走顺了，整体的开发能力才会变得更加硬核，更加自信。<br>当然，这话更多的是给我自己说的，共勉！</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hexo/tags/开发笔记/" rel="tag"># 开发笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hexo/2019/11/14/创新不易，而非不能；为学，须先立志/" rel="next" title="创新不易，而非不能；为学，须先立志">
                <i class="fa fa-chevron-left"></i> 创新不易，而非不能；为学，须先立志
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hexo/2019/12/06/我把电影天堂上的资源全给薅下来了/" rel="prev" title="我把电影天堂上的资源全给薅下来了">
                我把电影天堂上的资源全给薅下来了 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5bbb2338b87602f0" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTA1My8xNTU4MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description">学习总结</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hexo/archives/">
              
                  <span class="site-state-item-count">58</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hexo/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/hexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

</body>
</html>
